package socket

import (
	"fmt"
	"net"
)

type TCPServer struct {
	conn    net.Listener
	ip      string
	port    int
	nums    int
	clients []*net.Conn
}

func (t *TCPServer) Listen(ip string, port, nums int) {
	t.ip = ip
	t.port, t.nums = port, nums
	addr := fmt.Sprintf("%s:%d", t.ip, t.port)

	conn, e := net.Listen("tcp", addr)
	if e != nil {
		return
	}
	t.conn = conn
}

func (t *TCPServer) Accept(callback func(conn net.Conn)) {

	for {
		client, e := t.conn.Accept()
		if e != nil {
			continue
		}
		go callback(client)
	}
}

func DealClient(conn net.Conn) {
HERE:
	for {
		buf := make([]byte, 4)
		_, e := conn.Read(buf)
		if e != nil {
			panic(e)
		}
		fmt.Printf(">>%s<<\n", string(buf))
		buf = append(buf, []byte("yes")...)
		fmt.Println(string(buf))
		_, e = conn.Write(buf)
		if e != nil {
			fmt.Println(e.Error())
			goto HERE
		}
	}
}
